import React from 'react'
import {connect} from 'react-redux'
import {deepFullCopy, messages} from "share/common";
import { Button, message, Popover } from 'antd';
import {setSceneDefinition} from "actions/financial-account";
import SlideFrame from 'components/slide-frame';
import SearchArea from 'components/search-area';
import menuRoute from "routes/menuRoute";
import SceneRule from 'containers/financial-account/interface-definition/scene-rule';
import interfaceService from "containers/financial-account/interface-definition/interface-service";
import ResizeTable from 'components/resize-table'

class accountSceneDefinition extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      searchForm: [
        {
          type: 'input',
          id: 'sceneCodeOrName',
          label: messages('financial-account.key42')/*场景编码/名称*/
        }
      ],
      searchParams: {},
      columns: [
        {title: messages('financial-account.key43')/*场景编码*/,dataIndex: 'sceneCode', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key44')/*场景名称*/,dataIndex: 'sceneName', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key45')/*场景说明*/,dataIndex: 'comment', width: '20%', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key5')/*是否预置*/,dataIndex: 'isDefault', width: 96, render:(value) => value ? messages('common.yes')/*是*/ : messages('common.no')/*否*/},
        {title: messages('common.column.status')/*状态*/,dataIndex: 'isEnable', width: 80, render:(value) => value ? messages('common.valid')/*生效*/ : messages('financial-account.key6')/*不生效*/},
        {title: messages('common.operation')/*操作*/,dataIndex: 'operation', render: (value,record) => {
            return <span>
              {
                !record.isDefault && (
                  <span>
                    <a onClick={e => this.handleEdit(e,record)}>{messages('common.edit')/*编辑*/}</a>
                    <span className="ant-divider"/>
                  </span>
                )
              }
              <a onClick={e => this.handleGoDetail(e,record,'detail')}>{messages('financial-account.key46')/*指定核算业务*/}</a>
            </span>;}},
        {title: messages('financial-account.key47')/*核算要素定义*/,dataIndex: 'element', width: 120, render: (value,record) =>  <a onClick={e => this.handleGoDetail(e,record,'definition')}>{messages('financial-account.key47')/*核算要素定义*/}</a>},
        {title: messages('financial-account.key48')/*匹配组定义*/,dataIndex: 'mapping', width: 105, render: (value,record) =>  <a onClick={e => this.handleGoDetail(e,record,'setting')}>{messages('financial-account.key49')/*设置匹配组*/}</a>}
      ],
      data: [],
      loading: false,
      pagination: {
        total: 0
      },
      page: 0,
      showSlideFrame: false,
      title: '',
      editRecord: {},
      interfaceRecord: {},
      SceneDetail: menuRoute.getRouteItem('scene-detail'),
      ElementDefinition: menuRoute.getRouteItem('element-definition'),
      SettingMate: menuRoute.getRouteItem('setting-mate')
    }
  }

  componentDidMount() {
    this.props.dispatch(setSceneDefinition({}));
    this.setState({interfaceRecord: this.props.recordInfo}, () => {
      this.getList();
    });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({interfaceRecord: nextProps.recordInfo});
  }

  getList = () => {
    const { searchParams, page, interfaceRecord } = this.state;
    let temp = deepFullCopy(searchParams);
    Object.keys(temp).map(item => {
      !temp[item] && delete temp[item];
    });
    temp.page = page;
    temp.functionId = interfaceRecord.id;
    this.setState({loading: true});
    interfaceService.getSceneList(temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager,
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  search = (result) => {
    const { searchParams } = this.state;
    searchParams.sceneCodeOrName = result.sceneCodeOrName;
    this.setState({searchParams, page: 0},() => {
      this.getList();
    })
  };

  clear = () => {
    this.setState({searchParams: {}},() => {
      this.getList();
    })
  };

  handleEdit = (e,record) => {
    e.stopPropagation();
    this.setState({
      title: messages('financial-account.key50')/*编辑核算场景定义*/,
      editRecord: record
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  handleGoDetail = (e,record,type) => {
    e.stopPropagation();
    this.props.dispatch(setSceneDefinition(record));
    const { SceneDetail, ElementDefinition, SettingMate } = this.state;
    let url = type === 'detail' ? SceneDetail.url : (type === 'definition' ? ElementDefinition.url : SettingMate.url);
    this.context.router.push(url.replace(':tab','accounting-background-definition'));
  };

  handleNew = () => {
    this.setState({
      title: messages('financial-account.key51')/*新建核算场景定义*/,
      editRecord: {}
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  isRefresh = (isRefresh) => {
    this.setState({showSlideFrame: false});
    isRefresh === true && this.getList();
  };

  render(){
    const { searchForm, columns, data, loading, pagination, showSlideFrame, editRecord, title, interfaceRecord } = this.state;
    return(
      <div>
        <SearchArea searchForm={searchForm}
                    submitHandle={this.search}
                    clearHandle={this.clear}/>
        <div style={{margin:'10px 0px'}}>
          <Button type="primary" onClick={this.handleNew}>{messages('common.create')}</Button>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey={'id'}
          pagination={pagination}
          bordered/>
        <SlideFrame show={showSlideFrame}
                    title={title}
                    params={{
                      showSlideFrame,
                      editRecord,
                      interfaceRecord
                    }}
                    content={SceneRule}
                    onClose={(isRefresh) => this.isRefresh(isRefresh)}
                    afterClose={(isRefresh) => this.isRefresh(isRefresh)}/>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {

  }
}

accountSceneDefinition.contextTypes = {
  router: React.PropTypes.object
};

export default connect(mapStateToProps)(accountSceneDefinition);
